package ua.com.infinite.mobile.adapters;

import org.json.JSONObject;

import ua.com.infinite.mobile.App;
import ua.com.infinite.mobile.R;
import ua.com.infinite.mobile.contentprovider.InfiniteContentProvider;
import ua.com.infinite.mobile.db.DBAdapter;
import ua.com.infinite.mobile.db.TableNews;
import ua.com.infinite.mobile.plains.NewsItem;
import ua.com.infinite.mobile.server.Constants;
import ua.com.infinite.mobile.server.DataLoaderNews;
import ua.com.infinite.mobile.server.OnDownloadingListener;
import ua.com.infinite.mobile.server.OnUpdateUiListener;
import ua.com.infinite.mobile.server.RequestObject;
import ua.com.infinite.mobile.slidingmenu.fragments.TagsConst;
import ua.com.infinite.mobile.utils.imageloader.ImageLoader;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class AdapterNewsCursor extends CursorAdapter implements OnDownloadingListener {

	private String firstDate, lastDate;
	private String tag;
	private LayoutInflater layoutInflater;
	private Context context;
	private DBAdapter db;
	private Cursor cursor;
	private ImageLoader imageLoader;
	private DataLoaderNews dataLoaderNews;
	private OnUpdateUiListener onUpdateUiListener;

	public AdapterNewsCursor(Context context, Cursor c, OnUpdateUiListener onUpdateUiListener, String tag) {
		super(context, c);
		this.tag = tag;
		this.layoutInflater = LayoutInflater.from(context);
		this.context = context;
		this.db = new DBAdapter(context);
		this.imageLoader = new ImageLoader(context);
		this.onUpdateUiListener = onUpdateUiListener;
		if (cursor == null)
			update();
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		NewsItemHolder holder = (NewsItemHolder) view.getTag();
		int id = cursor.getInt(cursor.getColumnIndex(TableNews.COLUMN_ID));
		String poster_icon = cursor.getString(cursor.getColumnIndex(TableNews.COLUMN_POSTER_ICON));
		String poster_name = cursor.getString(cursor.getColumnIndex(TableNews.COLUMN_POSTER_NAME));
		String post_title = cursor.getString(cursor.getColumnIndex(TableNews.COLUMN_POST_TITLE));
		String post_text = cursor.getString(cursor.getColumnIndex(TableNews.COLUMN_POST_TEXT)).replace("<br />", "\n");
		String imgs_str = cursor.getString(cursor.getColumnIndex(TableNews.COLUMN_POST_IMGS));
		String date = cursor.getString(cursor.getColumnIndex(TableNews.COLUMN_DATE));
		
		imageLoader.DisplayImage(poster_icon, holder.poster_icon);
		holder.poster_name.setText(poster_name);
		holder.post_title.setText(post_title);
		holder.post_text.setText(post_text);
		holder.post_date.setText(date);
		if(!imgs_str.equals("")){
			String[] imgs_arr = imgs_str.split("\\|");
			holder.post_img.setVisibility(ImageView.VISIBLE);
			imageLoader.DisplayImage(imgs_arr[0], holder.post_img);
		}
		view.setId(id);
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup vg) {
		View row = layoutInflater.inflate(R.layout.news_row, null, true);
		NewsItemHolder holder = new NewsItemHolder();
		holder.poster_icon = (ImageView) row.findViewById(R.id.poster_icon);
		holder.poster_name = (TextView) row.findViewById(R.id.poster_name);
		holder.post_title = (TextView) row.findViewById(R.id.post_title);
		holder.post_text = (TextView) row.findViewById(R.id.post_text);
		holder.post_img = (ImageView) row.findViewById(R.id.post_img);
		holder.post_date = (TextView) row.findViewById(R.id.post_date);
		row.setTag(holder);
		return row;
	}

	public void update() {
		String selection = "";
		String[] selectionArgs = null;
		if (tag.equals(TagsConst.TAG_ALL)) {
			selection = null;
		} else if (tag.equals(TagsConst.TAG_PARTNER)) {
			selection = TableNews.COLUMN_TYPE + " LIKE ?";
			selectionArgs = new String[]{'%'+tag+'%'};
		} else {
			selection = TableNews.COLUMN_TYPE + "=?";
			selectionArgs = new String[]{tag};
		}
		this.cursor = context.getContentResolver().query(InfiniteContentProvider.CONTENT_URI_NEWS, null, selection, selectionArgs, TableNews.COLUMN_DATE+" DESC");
		if (cursor == null || !cursor.moveToFirst()) {
			dataLoaderNews = new DataLoaderNews(context, this, false);
			RequestObject requestObject = new RequestObject();
			requestObject.setAction(Constants.NEWS);
			requestObject.addParam(Constants.USER_ID, String.valueOf(App.getUser().getId()));
			startDownload(requestObject, false);

		} else {
			cursor.moveToLast();
			lastDate = cursor.getString(cursor.getColumnIndex(TableNews.COLUMN_DATE));
			cursor.moveToFirst();
			firstDate = cursor.getString(cursor.getColumnIndex(TableNews.COLUMN_DATE));
			changeCursor(cursor);
		}
	}

	public void updateByTyme(String mode) {
		RequestObject requestObject = new RequestObject();
		requestObject.setAction(Constants.NEWS);
		requestObject.addParam(Constants.USER_ID, String.valueOf(App.getUser().getId()));
		if (!mode.equals("")) {
			if (mode.equals(Constants.NEWS_NEW)) {
				requestObject.addParam(Constants.NEWS_UPD_TYEP, mode);
				requestObject.addParam(Constants.NEWS_DATE, firstDate);
			} else if (mode.equals(Constants.NEWS_OLD)) {
				requestObject.addParam(Constants.NEWS_UPD_TYEP, mode);
				requestObject.addParam(Constants.NEWS_DATE, lastDate);
			}
		}
		startDownload(requestObject, false);
	}
	
	public NewsItem getItem(int position){
		return db.getNewsItem(position);
	}

	static class NewsItemHolder {
		ImageView poster_icon;
		TextView poster_name;
		TextView post_title;
		TextView post_text;
		ImageView post_img;
		TextView post_date;
	}

	@Override
	public void startDownload(RequestObject request, boolean returnDataToCaller) {
		dataLoaderNews = new DataLoaderNews(context, this, returnDataToCaller);
		dataLoaderNews.execute(new RequestObject[] { request });
	}

	@Override
	public void onStartDownloading() {
		
	}

	@Override
	public void succesDownloading(boolean isSucces) {
		if (isSucces) {
			update();
		}
		onUpdateUiListener.updateUI(isSucces);
	}

	@Override
	public void returnData(JSONObject object) {
		
	}

}
